#include <QApplication>
#include <QMessageBox> // For error messages
#include <QDebug>
#include <QTextCodec> // 添加QTextCodec头文件
#include <QEventLoop> // Added for local event loop
#include <QMetaType>  // <--- 添加 QMetaType 头文件
#include "loginwindow.h"
#include "mainwindow.h"
#include "gui_bridge.h"
#include "sfts_client_api.h"
#include "client_wrapper.h"

// 全局主窗口实例，便于C回调函数回调
MainWindow *g_mainWindowInstance = nullptr; // This global instance might need careful management across login/logout cycles

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // Register QList<FileItem> for use in queued signal/slot connections
    // FileItem is an alias for FileItemData, which is declared with Q_DECLARE_METATYPE
    qRegisterMetaType<QList<FileItem>>("QList<FileItem>"); // <--- 添加类型注册

    // 设置Qt中文翻译
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    // 服务器配置
    QString serverIP = "127.0.0.1";
    int serverPort = 8888;

    // 创建ClientWrapper实例
    ClientWrapper clientWrapper;

    // 连接到服务器
    // This connection attempt should ideally be inside the loop or handled such that
    // it can be re-established if needed, or checked before each login attempt.
    // For now, keeping it outside the main application loop.
    if (!clientWrapper.connectToServer(serverIP, serverPort))
    {
        QMessageBox::critical(nullptr, QObject::tr("连接错误"),
                              QObject::tr("无法连接到服务器 %1:%2，请检查网络连接和服务器状态。")
                                  .arg(serverIP)
                                  .arg(serverPort));
        return 1; // Exit if can't connect initially
    }

    bool keepRunningApp = true;
    int lastLoginResult = QDialog::Rejected; // To track login dialog outcome

    while (keepRunningApp)
    {
        LoginWindow loginWindow(&clientWrapper);
        lastLoginResult = loginWindow.exec(); // Show login dialog modally

        if (lastLoginResult == QDialog::Accepted) // Login was successful (LoginWindow emitted accept())
        {
            QString loggedInUsername = loginWindow.getLastSuccessfulUsername(); // Use the new getter

            if (loggedInUsername.isEmpty())
            {
                // This case should ideally not happen if LoginWindow::onLoginResult correctly sets the username
                // and accept() is only called on actual success.
                qCritical() << "Login accepted, but no username retrieved. Cannot proceed.";
                keepRunningApp = false; // Or handle as a critical error, maybe retry login?
                continue;               // Skip to next iteration of the while loop, effectively exiting or retrying login
            }

            MainWindow mainWindow(loggedInUsername, &clientWrapper);
            g_mainWindowInstance = &mainWindow; // Update global instance

            QEventLoop mainWindowEventLoop; // Local event loop for MainWindow

            QObject::connect(&mainWindow, &MainWindow::loggedOut,
                             [&]()
                             {
                                 qDebug() << "Logout signal received, closing MainWindow and preparing for login.";
                                 // mainWindow.close(); // MainWindow should already be closing itself.
                                 // No explicit app.quit() here, we want the outer loop to continue.
                                 if (g_mainWindowInstance == &mainWindow)
                                     g_mainWindowInstance = nullptr;
                                 mainWindowEventLoop.quit(); // Exit the local event loop for MainWindow
                             });

            // If MainWindow is closed by any other means (e.g., user clicks X)
            QObject::connect(&mainWindow, &QMainWindow::destroyed,
                             [&]()
                             {
                                 qDebug() << "MainWindow destroyed.";
                                 if (g_mainWindowInstance == &mainWindow)
                                     g_mainWindowInstance = nullptr;
                                 if (mainWindowEventLoop.isRunning())
                                 {
                                     // This means it wasn't closed by loggedOut signal (which calls quit on loop)
                                     // So, consider this as quitting the app for now.
                                     keepRunningApp = false;
                                     mainWindowEventLoop.quit();
                                 }
                             });

            mainWindow.show();
            mainWindowEventLoop.exec(); // Run local event loop until mainWindow is closed and loop.quit() is called

            // After mainWindowEventLoop.exec() finishes, mainWindow is closed.
            // If it was due to logout, keepRunningApp is true, and loop continues to show LoginWindow.
            // If it was due to general close (X button), keepRunningApp should be false.
        }
        else // Login was cancelled or dialog closed
        {
            qDebug() << "Login dialog was closed or cancelled. Exiting application.";
            keepRunningApp = false; // Exit the while loop, and thus the application
        }
    }

    qDebug() << "Application finished.";
    return 0; // Normal application exit
}